package com.xlh.security;

import com.xlh.entity.UserEntity;
import com.xlh.enums.UserStatusEnum;
import com.xlh.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Spring Security配置
 *
 * @author cheer
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private RestAccessDeniedHandler restAccessDeniedHandler;

    @Autowired
    private RestAuthenticationFailureHandler restAuthenticationFailureHandler;

    @Autowired
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;

    @Autowired
    private RestLogoutSuccessHandler restLogoutSuccessHandler;

    @Autowired
    private LogoutHandler logoutHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //解决不能加载iframe的问题
        http.headers().frameOptions().disable();

        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter("/unauthorized/form", "POST");
        validateCodeFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);

        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                //自定义登录页
                .loginPage("/login")
                .loginProcessingUrl("/unauthorized/form")
                .successHandler(restAuthenticationSuccessHandler)
                .failureHandler(restAuthenticationFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/unauthorized/**", "/user/create",
                        "/webjars/**","/swagger-ui.html/**","/druid/**", "/login.html")// 对登录要允许匿名访问
                .permitAll()
                .anyRequest()// 除上面外的所有请求全部需要鉴权认证
                .authenticated()
                .and()
                .csrf()
                .disable();


        // 设置session
        http.sessionManagement().and().sessionManagement()
                .maximumSessions(10)
                .sessionRegistry(getSessionRegistry());

        //添加自定义未授权和未登录结果返回
        http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint)
                .and().exceptionHandling().accessDeniedHandler(restAccessDeniedHandler);

        //添加注销接口
        http.logout()
                .logoutUrl("/logout")
                .addLogoutHandler(logoutHandler)
                .logoutSuccessHandler(restLogoutSuccessHandler)
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            List<UserEntity> users = userService.listUserInfo(username);
            if (CollectionUtils.isEmpty(users)) {
                throw new UsernameNotFoundException("");
            }
            List<UserEntity> data = users.stream()
                    .filter(user -> UserStatusEnum.getByCode(user.getStatus()) == UserStatusEnum.NOT_DELETE)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(data)) {
                return new CustomUserDetails(data.get(data.size() - 1));
            }

            List<UserEntity> accountCancellationData = users.stream()
                    .filter(user -> UserStatusEnum.getByCode(user.getStatus()) == UserStatusEnum.ACCOUNT_CANCELLATION)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(accountCancellationData)) {
                return new CustomUserDetails(accountCancellationData.get(accountCancellationData.size() - 1));
            }
            throw new UsernameNotFoundException("");
        };
    }

    @Bean
    public SessionRegistry getSessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
    }

}
